var models = require('../db/db');
var express = require('express');
var router = express.Router();
var path = require('path')
var fs = require('fs');
var createBucket = require('../tencentup/createBucket')

var jsonWrite = function(res, ret) {
    if(typeof ret === 'undefined') {
        res.send('err');
    } else {
        console.log(ret);
        res.send(ret);
    }
}

var dateStr = function(str) {
    return new Date(str.slice(0,7));
}

// function readFileList(paths) {
// // 遍历upload_tmp文件夹里面的所有流文件，待所有流读取到upload文件夹完毕再删除
//   var files = fs.readdirSync(paths)
//   files.forEach(function (itm, index) {
//       var stat = fs.statSync(path.join(paths,itm))
//       if (stat.isDirectory()) {
//         //递归读取文件夹
//           readFileList(paths + itm + "/")
//       } else {
//          // 删除流文件
//           fs.unlink(path.join(paths , itm),function(err){
//             if (err){
//               return console.log(err)
//             }
//           })
//       }
//   })
// }

// router.post('/uploadTencent',(req,res)=>{
//   var des_file = "./upload/" + req.files[0].originalname
//   fs.readFile( req.files[0].path, function (err, data) {
//     fs.writeFile(des_file, data, function (err) {
//         console.log(des_file,'des_file')
//         if( err ){
//             console.log( err )
//         }else{
//           response = {
//               message:'File uploaded successfully',
//               filename:req.files[0].originalname
//           }
//           readFileList(path.resolve(__dirname,'../upload_tmp/'))//删除流文件
//           res.end( JSON.stringify( response ))
//         }
//     })
//   })
// })

function readFileList(paths,req) {
    // 遍历upload_tmp文件夹里面的所有流文件，待所有流读取到upload文件夹完毕再删除
      var files = fs.readdirSync(paths)
      files.forEach(function (itm, index) {
        //   itm:文件名,文件绝对路径:path.join(paths,itm)
          var stat = fs.statSync(path.join(paths,itm))
          if (stat.isDirectory()) {
            //递归读取文件夹
              readFileList(paths + itm + "/")
          } else {
            createBucket(itm,req)
          }
      })
    }
    router.post('/uploadTencent',(req,res)=>{
      var des_file = "./upload/" + req.files[0].originalname
      fs.readFile( req.files[0].path, function (err, data) {
        fs.writeFile(des_file, data, function (err) {
            if( err ){
                console.log( err )
            }else{
                readFileList(path.resolve(__dirname,'../upload/'),req)
              response = {
                  message:'File uploaded successfully',
                  filename:req.files[0].originalname
              }

            //   readFileList(path.resolve(__dirname,'../upload_tmp/'))//删除流文件
              res.end( JSON.stringify( response ))
            }
        })
      })
    })

module.exports = router;